package org.liaohailong.helloworld.study;

/**
 * Author: liaohailong
 * Time: 2021/4/30 16:43
 * Describe: 队列与广度优先
 */
public class QueueTest {
    /*
    输入：grid = [
    ["1","1","1","1","0"],
    ["1","1","0","1","0"],
    ["1","1","0","0","0"],
    ["0","0","0","0","0"]
    ]
    输出：1
     * */
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                char c = grid[i][j];
                if (c == '1') {
                    count++;
                    traversal(grid, i, j);
                }
            }
        }
        return count;
    }

    private void traversal(char[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[i].length) return;

        char c = grid[i][j];
        if (c == '0') return;

        grid[i][j] = '0';

        traversal(grid, i, j - 1); // 上
        traversal(grid, i, j + 1); // 下
        traversal(grid, i - 1, j); // 左
        traversal(grid, i + 1, j); // 右
    }
}
